package com.controller;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.beans.UserInfo;
import com.service.UserService;

@Controller  @RequestMapping("/user")
public class UserController {
	@Resource
	private UserService userService;
	
	//用于国际化
	@Resource 
	private MessageSource messageSource;
	
	//全局的,用于转向某个页面
	@GetMapping("/{page}")
	public String toPage(@PathVariable("page") String page) {
		return page;   //默认会转向 src/main/resources/templates/+page+.html
	}
	
	//添加用户
	@PostMapping("/add")
	public String add(UserInfo user,ModelMap m)
	{
		userService.add_user(user);
		m.put("msg","用户添加成功");
		return "###";
	}
	
	@GetMapping("/getAll")
	public String getAll(ModelMap m) {
		List<UserInfo> userList= userService.select_all();
		m.put("userList",userList);
		m.put("size",userList.size());
		return "###";	
	}

	
	@GetMapping("/update")
	public String searchForUpdate(int id,ModelMap m) {
		UserInfo user=userService.get_user(id);
		m.put("user", user);
		return "###"; 
	}

	@PostMapping("/update")
	public String update(UserInfo user,ModelMap m) {
		m.put("user",user);
		userService.update_user(user);
		m.put("msg","用户信息更新成功");
		return "###"; 
	}
	
	
	@GetMapping("/updatep")
	public String searchForUpdatep(int id,ModelMap m) {
		UserInfo user=userService.get_user(id);
		m.put("user", user);
		return "###"; 
	}
	
	@PostMapping("/updatep")
	public String updatep(UserInfo user,ModelMap m) {
		m.put("user",user);
		userService.update_user(user);
		m.put("msg","个人信息更新成功");
		return "###"; 
	}
	
	@GetMapping("/delete")
	public String delete(int id) {
		userService.del_user(id);
		return "###";	
	}
	
	//登录
	@PostMapping("/login")
	 public String login(String userName,String password,String type, ModelMap m,HttpSession session, ModelMap model) {
	  UserInfo user=userService.login(userName,password);
	  if(user!=null)
	  { 
	   if(user.getType().equals("管理员")) {
	    session.setAttribute("session_user",user);
	    model.addAttribute("userName",user.getUserName());
	    return "admine-index";
	   }
	   else
	   {
	    session.setAttribute("session_user",user);
	    model.addAttribute("userName",user.getUserName());
	    return "index";
	   }
	  }
	  else {
	   m.put("msg", "用户名或密码错误,登录失败"); 
	   return "login"; 
	  }
	 }
}
